<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ report.reportName }}</span>
        <el-button style="float: right;" size="mini" @click="goBack">
          <i class="el-icon-back"></i> 返回
        </el-button>
      </div>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="报表编码">{{ report.reportCode }}</el-descriptions-item>
        <el-descriptions-item label="报表名称">{{ report.reportName }}</el-descriptions-item>
        <el-descriptions-item label="报表类型">
          <dict-tag :options="dict.type.report_type" :value="report.reportType"/>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="dict.type.common_status" :value="report.reportStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="权限标识" :span="2">{{ report.permissionCode }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ report.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ report.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ report.remark }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">报表参数</el-divider>
      
      <el-form :model="paramForm" ref="paramForm" :inline="true" label-width="100px" class="demo-form-inline">
        <el-form-item 
          v-for="param in parameters" 
          :key="param.paramId" 
          :label="param.paramName" 
          :prop="param.paramKey"
          :rules="{ required: param.required === 1, message: `请输入${param.paramName}`, trigger: 'blur' }"
        >
          <!-- 字符串类型参数 -->
          <el-input 
            v-if="param.paramType === 'string'" 
            v-model="paramForm[param.paramKey]" 
            :placeholder="`请输入${param.paramName}`">
          </el-input>
          
          <!-- 数值类型参数 -->
          <el-input-number 
            v-if="param.paramType === 'number'" 
            v-model="paramForm[param.paramKey]" 
            :controls="true">
          </el-input-number>
          
          <!-- 日期类型参数 -->
          <el-date-picker
            v-if="param.paramType === 'date'"
            v-model="paramForm[param.paramKey]"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
          
          <!-- 日期时间类型参数 -->
          <el-date-picker
            v-if="param.paramType === 'datetime'"
            v-model="paramForm[param.paramKey]"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
          
          <!-- 布尔类型参数 -->
          <el-switch
            v-if="param.paramType === 'boolean'"
            v-model="paramForm[param.paramKey]">
          </el-switch>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="executeReport">执行</el-button>
          <el-button type="success" @click="exportReportData">导出</el-button>
        </el-form-item>
      </el-form>

      <el-divider content-position="left">报表数据</el-divider>
      
      <!-- 表格类报表 -->
      <el-table
        v-if="report.reportType === '0' && reportData.columns && reportData.columns.length > 0"
        :data="reportData.data"
        border
        style="width: 100%">
        <el-table-column
          v-for="column in reportData.columns"
          :key="column"
          :prop="column"
          :label="column"
          align="center">
        </el-table-column>
      </el-table>
      
      <!-- 图表类报表 -->
      <div 
        v-if="report.reportType === '1' && reportData.columns && reportData.columns.length > 0" 
        id="chartContainer" 
        style="width: 100%; height: 400px;">
      </div>
      
      <!-- 混合类报表 -->
      <div v-if="report.reportType === '2' && reportData.columns && reportData.columns.length > 0">
        <el-row :gutter="20">
          <el-col :span="24">
            <div id="mixedChartContainer" style="width: 100%; height: 300px;"></div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <el-table
              :data="reportData.data"
              border
              style="width: 100%">
              <el-table-column
                v-for="column in reportData.columns"
                :key="column"
                :prop="column"
                :label="column"
                align="center">
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
      
      <el-empty v-if="!reportData.columns || reportData.columns.length === 0" description="暂无数据"></el-empty>
    </el-card>
  </div>
</template>

<script>
import { getReport } from "@/api/report/report";
import { getReportParameters, executeReport, exportReportData } from "@/api/report/report";
import * as echarts from 'echarts';

export default {
  name: "ReportView",
  dicts: ['report_type', 'common_status'],
  data() {
    return {
      // 报表ID
      reportId: null,
      // 报表信息
      report: {},
      // 报表参数
      parameters: [],
      // 参数表单
      paramForm: {},
      // 报表数据
      reportData: {},
      // 图表实例
      chart: null,
      // 混合图表实例
      mixedChart: null
    };
  },
  created() {
    this.reportId = this.$route.params.id;
    this.getReportInfo();
    this.getParameters();
  },
  mounted() {
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
    if (this.mixedChart) {
      this.mixedChart.dispose();
      this.mixedChart = null;
    }
  },
  methods: {
    // 获取报表信息
    getReportInfo() {
      getReport(this.reportId).then(response => {
        this.report = response.data;
      });
    },
    
    // 获取报表参数
    getParameters() {
      getReportParameters(this.reportId).then(response => {
        this.parameters = response.data || [];
        
        // 初始化参数表单
        const form = {};
        this.parameters.forEach(param => {
          // 根据参数类型设置默认值
          let defaultValue = param.defaultValue;
          
          if (param.paramType === 'number') {
            defaultValue = defaultValue ? parseFloat(defaultValue) : 0;
          } else if (param.paramType === 'boolean') {
            defaultValue = defaultValue === 'true' || defaultValue === '1';
          } else if (param.paramType === 'date' || param.paramType === 'datetime') {
            defaultValue = defaultValue ? new Date(defaultValue) : new Date();
          }
          
          form[param.paramKey] = defaultValue;
        });
        
        this.paramForm = form;
      });
    },
    
    // 执行报表
    executeReport() {
      this.$refs.paramForm.validate(valid => {
        if (valid) {
          // 处理日期参数格式
          const params = { ...this.paramForm };
          
          Object.keys(params).forEach(key => {
            if (params[key] instanceof Date) {
              params[key] = this.formatDate(params[key]);
            }
          });
          
          executeReport(this.reportId, params).then(response => {
            this.reportData = response.data || {};
            
            this.$nextTick(() => {
              if (this.report.reportType === '1') {
                this.renderChart();
              } else if (this.report.reportType === '2') {
                this.renderMixedChart();
              }
            });
          });
        }
      });
    },
    
    // 导出报表数据
    exportReportData() {
      this.$refs.paramForm.validate(valid => {
        if (valid) {
          // 处理日期参数格式
          const params = { ...this.paramForm };
          
          Object.keys(params).forEach(key => {
            if (params[key] instanceof Date) {
              params[key] = this.formatDate(params[key]);
            }
          });
          
          const reportName = this.report.reportName || '报表';
          // 使用通用下载方法
          this.$download.excel(`/rpt/viewer/export/${this.reportId}`, params, reportName);
        }
      });
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) {
        return '';
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 渲染图表
    renderChart() {
      if (!this.reportData.data || this.reportData.data.length === 0) {
        return;
      }
      
      if (!this.chart) {
        this.chart = echarts.init(document.getElementById('chartContainer'));
      }
      
      // 假设第一列为X轴，第二列为Y轴
      const xField = this.reportData.columns[0];
      const yField = this.reportData.columns[1];
      
      const xData = this.reportData.data.map(item => item[xField]);
      const yData = this.reportData.data.map(item => item[yField]);
      
      const option = {
        title: {
          text: this.report.reportName
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: yData,
          type: 'bar'
        }]
      };
      
      this.chart.setOption(option);
    },
    
    // 渲染混合图表
    renderMixedChart() {
      if (!this.reportData.data || this.reportData.data.length === 0) {
        return;
      }
      
      if (!this.mixedChart) {
        this.mixedChart = echarts.init(document.getElementById('mixedChartContainer'));
      }
      
      // 假设第一列为X轴，第二列为Y轴
      const xField = this.reportData.columns[0];
      const yField = this.reportData.columns[1];
      
      const xData = this.reportData.data.map(item => item[xField]);
      const yData = this.reportData.data.map(item => item[yField]);
      
      const option = {
        title: {
          text: this.report.reportName
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: yData,
          type: 'line'
        }]
      };
      
      this.mixedChart.setOption(option);
    },
    
    // 调整图表大小
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
      if (this.mixedChart) {
        this.mixedChart.resize();
      }
    },
    
    // 返回列表页
    goBack() {
      this.$router.push({ path: '/report/list' });
    }
  }
};
</script>

<style scoped>
.el-divider {
  margin: 24px 0;
}
</style> 